<template>
    <div class="updata">
        <el-form ref="formRef" :rules="data.rules" :model="data.user" style="padding: 20px 30px 10px 0">
                <el-form-item prop="password" label="原密码" >
                    <el-input show-password v-model="data.user.password" autocomplete="off" prefix-icon="Lock" placeholder="请输入密码"/>
                </el-form-item>
                <el-form-item prop="newPassword" label="新密码" >
                    <el-input show-password v-model="data.user.newPassword" autocomplete="off" prefix-icon="Lock" placeholder="请输入密码"/>
                </el-form-item>
                <el-form-item prop="new2Password" label="确认新密码" >
                    <el-input show-password v-model="data.user.new2Password" autocomplete="off" prefix-icon="Lock" placeholder="请输入密码"/>
                </el-form-item>
            </el-form>
            <div class="footer">
                <el-button @click="data.formVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">保 存</el-button>
            </div>
    </div>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import request from '../utils/request'

const formRef = ref()
const validatePass = (rule, value, callback) => {
  // value 表示用户输入的确认密码
  if (value !== data.user.newPassword) {
    callback(new Error("两次输入的密码不匹配！"))
  } else {
    callback()
  }
}
const data=reactive({
    user: JSON.parse(localStorage.getItem('code_user')||'{}'),
    rules:{
        password:[
            {required:true,message:'请输入原密码',trigger:'blur'}
        ],
        newPassword:[
            {required:true,message:'请输入新密码',trigger:'blur'}
        ],
        new2Password:[{required:true,message:"请再次输入密码",trigger:"blur"},
            {validator:validatePass,trigger:"blur"}
        ]
    }
})

const save=()=>{
    formRef.value.validate((valid) => {
        if (valid) {
            request.post('/updatePassword',data.user).then(res=>{
        if(res.code==200){
            ElMessage.success(res.msg)
            setTimeout(()=>{
                localStorage.removeItem('code_user')
                location.href='/login'
            },1000)
        }else{
            ElMessage.error(res.msg)
        }
    })
        }
    }) 
}

</script>
<style scoped lang="scss">
.updata{
    width: 50%;
    height: 50%;
    background-color: #F0F2F5;
    padding: 10px;
    border-radius: 10px;

    .footer{
        text-align: center;
        padding-bottom: 10px;
    }
}
</style>